package com.okilo.online.app.apt

import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.okilo.online.app.R
import com.okilo.online.app.event.OkiloEventPointType
import com.okilo.online.app.request.HttpHelper
import com.okilo.online.app.tools.OkiloDensityUtil
import com.okilo.online.app.tools.apt.OkiloRecyclerViewAdapter
import com.okilo.online.app.tools.apt.OkiloViewHolderHelper
import com.okilo.online.app.tools.decoration.LinearSpacingItemDecoration
import com.okilo.online.app.apt.OkiloStepGeneralApt
import com.okilo.online.app.dialog.OkiloSelectPopup
import org.json.JSONObject

/**
 * OkiloLoan
 * @Author wwdeng
 * @CreateTime: 2024/11/19 10:43
 * @Annotation：流程 - 联系人适配器
 */
class OkiloStepContactApt(private val parentView: ViewGroup?, recyclerView: RecyclerView?) :
    OkiloRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.okilo_fmt_step_contact_item) {

    /**
     * 选择联系电话监听
     */
    private var chooseMobileListsner: IChildItemSelectMobileListener? = null
    fun setOnChildItemSelectMobileListener(listener: IChildItemSelectMobileListener){
        chooseMobileListsner = listener
    }

    override fun fillData(helper: OkiloViewHolderHelper, position: Int, model: JSONObject) {
        val okiloProcessStepContactIndex = helper.getTextView(R.id.okiloProcessStepContactIndex)
        var showContactIndex = String.format(mContext.getString(R.string.okilo_process_step_contact_info_index),"${position+1}")
        if (position > 0){
            showContactIndex = "$showContactIndex ${mContext.getString(R.string.okilo_process_step_contact_info_different)}"
        }
        okiloProcessStepContactIndex.text = showContactIndex

        val okiloProcessStepContactListView = helper.getView<RecyclerView>(R.id.okiloProcessStepContactListView)
        okiloProcessStepContactListView.setHasFixedSize(true)
        okiloProcessStepContactListView.isNestedScrollingEnabled = false
        okiloProcessStepContactListView.isFocusableInTouchMode = false //不需要焦点
        okiloProcessStepContactListView.layoutManager = LinearLayoutManager(mContext)
        if (okiloProcessStepContactListView.itemDecorationCount == 0){
            val topDecoration = OkiloDensityUtil.dp2px(16f)
            okiloProcessStepContactListView.addItemDecoration(
                LinearSpacingItemDecoration(
                    0,
                    0,
                    0,
                    topDecoration
                )
            )
        }
        val adapter = OkiloStepGeneralApt(okiloProcessStepContactListView)
        okiloProcessStepContactListView.adapter = adapter
        okiloProcessStepContactListView.itemAnimator = DefaultItemAnimator()
        adapter.setOnItemChildClickListener { _, childView, childPosition ->
            val childModel = adapter.getItem(childPosition)
            when(childModel.optString("action")){
                "CONTACT_GROUP_RELATION" -> {//选择
                    val dataList = arrayListOf<JSONObject>()
                    val dataArray = childModel.optJSONArray("values")
                    if (dataArray != null) {
                        for (i in 0..<dataArray.length()) {
                            dataList.add(dataArray.optJSONObject(i))
                        }
                    }
                    showPopupwindow(childView, dataList) { data ->

                        //选择的Other需要设置为空
                        data?.put("otherValue","")
                        childModel.put("selectItem", data)
                        adapter.notifyItemChanged(childPosition)

                        val subRemark = "${data?.optString("value")}$$${data?.optString("duration")}"
                        HttpHelper.addPoint(String.Companion.format(OkiloEventPointType.OKILO_CLICK_TRACK.STEP_XX_SELECT,"${model.optString("stepTitle")}_${childModel.optString("paramName")}_${position+1}"), subRemark)
                    }
                }
                "CONTACT_GROUP_PHONE" -> {//联系电话
                    if (chooseMobileListsner != null){
                        chooseMobileListsner?.onChildSelectMobileClick(position,childModel)
                    }
                }
            }
        }

        val dataArray = model.optJSONArray("dataList")
        val dataList = arrayListOf<JSONObject>()
        if (dataArray != null) {
            for (i in 0..<dataArray.length()){
                val contactItem = dataArray.optJSONObject(i)
                contactItem.put("stepTitle",model.optString("stepTitle"))
                contactItem.put("stepType","CONTACT")
                contactItem.put("stepItemIndex",position+1)
                dataList.add(contactItem)
            }
        }
        adapter.data = dataList

        if (position == itemCount - 1){
            helper.setVisibility(R.id.okiloProcessStepContactItemLine, View.GONE)
        } else {
            helper.setVisibility(R.id.okiloProcessStepContactItemLine, View.VISIBLE)
        }
    }

    /**
     * choose Mobile
     */
    interface IChildItemSelectMobileListener{
        fun onChildSelectMobileClick(parentPosition: Int,childModel: JSONObject)
    }

    /**
     * SELECT
     */
    fun interface IChildItemSelectListener{
        fun onChildSelectClick(data: JSONObject?)
    }

    /**
     * 选择选项
     */
    private fun showPopupwindow(view: View, dataList: ArrayList<JSONObject>, listener: IChildItemSelectListener){
        val selectPopup = OkiloSelectPopup(mContext)
        selectPopup.setWindowWidth(view.width + OkiloDensityUtil.dp2px(10f))
        selectPopup.setSelectItemListener(object : OkiloSelectPopup.IItemClickListener {
            //完成
            override fun onConfirmAction(data: JSONObject?) {
                listener.onChildSelectClick(data)
            }
            //关闭监听
            override fun onDismissListener() {
            }
        })
        parentView?.let {
            selectPopup.show(view, it)
            selectPopup.setBrandList(dataList)
        }
    }
}